package dao

import (
	"hcy-api/structs/tables"
	"sys/global"
)

var OrgRepository = new(orgRepository)

type orgRepository struct{}

// CheckIsExist 检查部门是否已经存在，b-true 存在
func (r orgRepository) CheckIsExist(parentId int64, name string) (b bool, err error) {
	var num int64
	err = global.DB.Model(&tables.Org{}).Where(&tables.Org{ParentId: parentId, OrgName: name}).Count(&num).Error
	if err != nil {
		return false, err
	}
	b = num > 0
	return b, nil
}

func (r orgRepository) Create(u *tables.Org) error {
	return global.DB.Create(&u).Error
}
func (r orgRepository) FindById(orgId int64) (u *tables.Org, err error) {
	err = global.DB.Where(&tables.Org{Id: orgId}).Find(&u).Error
	return
}
func (r orgRepository) UpdateById(u *tables.Org) (err error) {
	var d = new(tables.Org)
	err = global.DB.Where(&tables.Org{Id: u.Id}).First(&d).Error
	if err != nil {
		return err
	}
	return global.DB.Save(&u).Error
}

// FindAll 查询全部未被删除的组织
func (r orgRepository) FindAll() (li []tables.Org, err error) {
	err = global.DB.Model(&tables.Org{}).Find(&li).Error
	return
}

func (r orgRepository) DeleteById(orgId int64) (err error) {
	err = global.DB.Model(&tables.Org{}).Delete(&tables.Org{Id: orgId}).Error
	return err
}

// FindUserList 查询部门下的全部用户
func (r orgRepository) FindUserList(orgId int64) (li []tables.User, err error) {
	err = global.DB.Model(&tables.User{}).Where(" user_id in (select user_id from sys_map_user_org where org_id =?)", orgId).Find(&li).Error
	return
}
